package com.cqupt.scanning.system.acl.service.impl;

import cn.hutool.core.util.StrUtil;
import com.cqupt.scanning.security.entity.SysUser;
import com.cqupt.scanning.security.entity.User;
import com.cqupt.scanning.system.acl.entity.AclUser;
import com.cqupt.scanning.system.acl.service.AclPermissionService;
import com.cqupt.scanning.system.acl.service.AclUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 用户认证、权限
 * @ClassName: SelfUserDetailsService
 * @Date: 2021/1/5 22:42
 * @Author: 宋宝梁
 */

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private AclUserService aclUserService;
    private AclPermissionService aclPermissionService;

    @Autowired
    public UserDetailsServiceImpl(AclUserService aclUserService, AclPermissionService aclPermissionService) {
        this.aclUserService = aclUserService;
        this.aclPermissionService = aclPermissionService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) {
        AclUser aclUser = aclUserService.selectByUsername(username);
        User user = new User();
        BeanUtils.copyProperties(aclUser, user);
        SysUser sysUser = new SysUser(user);
        List<String> permissionValueList = new ArrayList<>();
        String sysNote = aclUser.getNote();
        // 系统用户
        if (StrUtil.equals(sysNote, "1")) {
            permissionValueList = aclPermissionService.selectPermissionValueByUserId(aclUser.getId());
            sysUser.setPermissionValueList(permissionValueList); // 存入当前用户的权限
        }
        // 设备用户
        if (StrUtil.equals(sysNote, "0")) {
            String roleType = aclUser.getType();
            permissionValueList.add(roleType);
            sysUser.setPermissionValueList(permissionValueList);
        }
        return sysUser;
    }
}
